<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>web sk</title>
  </head>
  <body>
    <input type="text" id="messageInput" placeholder="Enter message" />
    <button id="sendButton">Send</button>
    <ul id="socket-ul"></ul>
  </body>
</html>
<script>
  const socket = new WebSocket("ws://localhost:8080"); // 绑定服务
  // 监听
  socket.addEventListener("open", (event) => {
    console.log("监听socket的链接");
  });
  // 监听socket的服务端发送的消息
  socket.addEventListener("message", (event) => {
    console.log(`客户端收到消息内容: ${event.data}`);
    const li = document.createElement("li");
    li.innerText = event.data;
    document.getElementById("socket-ul").appendChild(li);
  });
  document.getElementById("sendButton").addEventListener("click", (event) => {
    const inputVal = document.getElementById("messageInput").value;
    socket.send(inputVal); // 给服务器发送输入框内容
    document.getElementById("messageInput").value = ""; // 清空input
  });
</script>
